# -*- coding: utf-8 *-*


class DBActors():

    def __init__(self, filename):
        self.filename = filename
        self.file = None
        self.currentline = None

    def open(self):
        if self.file is None:
            self.file = open(self.filename)

            # Read file until the start of actor/actress list
            while self.currentline != '----			------\n':
                self.currentline = self.file.readline()
        else:
            raise Exception('Already opened!')

    def close(self):
        self.file.close()
        self.file = None

    def next(self):
        self.currentline = self.file.readline()

        if self.finished():
            return None, None

        parts = self.currentline.split('\t')

        actor = None
        title = None

        if self.is_actor_line():

            actor = parts[0].strip()
            title = self.get_movie_name(parts, 1)

        elif self.is_movie_line():
            title = self.get_movie_name(parts)

        return actor, title

    def finished(self):
        return self.end_of_db() or self.end_of_list()

    def end_of_db(self):
        return self.currentline == ''

    def end_of_list(self):
        return self.currentline.startswith('---------------------------------')

    def is_actor_line(self):
        first = self.currentline[0]
        return first != '\t' and first != '\n'

    def is_movie_line(self):
        return self.currentline[0] == '\t'

    def find_non_empty(self, parts, startat=0):
        for index in range(startat, len(parts)):
            part = parts[index]
            if part != '':
                return part

    def get_movie_name(self, parts, startat=0):
        title = self.find_non_empty(parts, startat)

        characterStart = title.find('[')
        creditStart = title.find('<')

        if characterStart > 0:
            title = title[:characterStart]
        elif creditStart > 0:
            title = title[:creditStart]

        return title.strip()
